/*公共*/
/**
 * 登录弹窗控件
 * @returns
 */
var $loginCompents = {
    /**
     * 属性声明
     */
    //组件id
    "compent" : null,
    "lang" : {
        "regist": {
            "9": "您还没有接受注册协议" ,
            "2": "验证码错误！",
            "4": "帐号已被使用！",
            "3": "帐号已被使用！" ,
            "1": "验证码错误！",
            "5": "手机验证码错误！",
            "11" : "验证码不能为空",
            "0": "注册失败！"
        },
        "active": {
            "1" : "未找到匹配的号码，请核对和再输入。",
            "9": "您还没有接受注册协议" ,
            "2": "验证码错误！",
            "4": "此帐号已注册，请尝试登录！",
            "3": "此帐号已注册，请尝试登录！" ,
            "5": "手机验证码错误！",
            "0": "注册失败！",
        },
       "username" : {
           "-6" : "用户名已存在,请尝试激活" , 
           "-5" : "用户名不能含有非法字符",
           "0"  : "请输入邮箱或手机号码",
           "-4" : "请输入用户名" ,
           "-3" : "用户名长度错误" ,
           "-2" : "请输入正确的手机号码" ,
           "-1" : "您输入的用户名不存在。" ,
       } ,
       "password" : {
           "-4" : "请输入密码" ,
           "-3" : "密码长度应在6~20之间" ,
           "-2" : "密码中不能含有特殊符号"
       },
       "confirmPassword" : {
           "-4" : "请再次输入密码" ,
           "-3" : "密码长度不正确" ,
           "-2" : "两次输入的密码不一致"
       },
       "captcha" : {
           "-4" : "验证码不能为空" ,
           "-3" : "验证码长度错误" 
       } ,
       "verifycode" :{
           "-4" : "手机校验码不能为空" ,
           "-3" : "手机校验码长度错误" ,
           "-2" : "手机校验码错误" ,
       }
    } ,
    
    /**
     * 公共方法声明
     */
    //显示登录窗
    "showLogin" : function () {
        if (!this.compent) {
            // $.include([
            //     '/themes/ugo/css/2013_v1/login_pop.css']);
            
            $.getJSON("/flow/auth/showLogin" , function(data){
                if (!data || data.code !== 0) {
                    return false;
                }
                $("body").append(data.data);
                $loginCompents.init();
            }) ;
        } else {
            this.compent.show();
        }
    },
    
    //显示错误信息
    "showError" : function (object , message) {
        $(object).parents('div.l,div.dlinput').find('.tip6').remove();
        $(object).parents('div.l,div.dlinput').append('<div class="tip6">' + message + '</div>');
        console.log($(object).parents('div.l,div.dlinput'));
        $(object).addClass('oninp');
//        $(object).bind('change' , $loginCompents.hideError);
    },
    
    //关闭错误提示
    "hideError" : function (object) {
//        $(object).change(function () {
            $(object).parents('div.l,div.dlinput').find('.tip6').remove();
            $(object).removeClass('oninp');
//        });
//        $(this).unbind('change' , $loginCompents.hideError);
    },
    
    //验证码发送间隔
    "verfiyCodeInterval" : 0 ,
    
    /**
     * 初始化方法
     */
    "init" : function () {
        this.compent = $("#showlogin");
        this.compent.show();
        //初始化切换按钮
        var i = 0;
        this.compent.find('ul#tab_t li').each(function(){
            $(this).attr('attach_id',i);
            $(this).click(function(){
                $loginCompents.compent.find('ul#tab_t li').removeClass('cur');
                $(this).addClass('cur');
                $loginCompents.eventTabClick($(this).attr('attach_id'));
            });
            i++;
        });
        //其他切换按钮
        this.compent.find('.aa .b1').click(
            function(){$loginCompents.compent.find('ul#tab_t li').get(1).click();}
        );
        this.compent.find('.bb .b2').click(
            function(){$loginCompents.compent.find('ul#tab_t li').get(2).click();}
        );

        this.compent.find(".yimg img, .yimg em").click($loginCompents.eventCaptchaClick); //验证码功能
        this.compent.find("a.verfiy_code_btn").click($loginCompents.eventVerfiyCodeClick);    //手机验证码
        this.compent.find("#closex2").click($loginCompents.eventCloseBtnClick);
        this.formInit();
    } ,
    
    //表单校验初始化
    "formInit" : function () {
        //输入框校验
        $("#login_form input").change($loginCompents.loginFormValidate);
        //提交按钮
        $("#login_form button#login_btn").click($loginCompents.loginFormValidate);
        //注册校验
        $("#regist_form input").change($loginCompents.registFormValidate);
        //注册按钮校验
        $("#regist_form button#regist_btn").click($loginCompents.registFormValidate);
        //激活校验
        $("#active_form input").change($loginCompents.activeFormValidate);
        //注册按钮校验
        $("#active_form button#active_btn").click($loginCompents.activeFormValidate);
    },
    
    //登录校验
    "loginFormValidate" : function () {
        var error = false;
        var is_submit = ($(this).attr("id") == 'login_btn');
        var name_type = 0;
        var $form = $("#login_form");
        var object_name = (!this.name) ? "" : this.name; //表单名
        if (!is_submit) {
            $loginCompents.hideError(this); //关闭层显示
        }
        //密码
        if (object_name == "password" || is_submit) {
            var code = ($loginCompents._validatePassword($form.find('input[name=password]').val())); 
            if (code<0) {
                $loginCompents.showError($form.find("input[name=password]") , $loginCompents.lang.password[code]);
                error = true;
            }
        }
        //用户名
        if (object_name == "username") {
            return $loginCompents.checkUserName($form.find("input[name=username]") , function (obj , response) {
                if (response.code !== 0) { //用户不存在
                    $loginCompents.showError(obj , $loginCompents.lang.username[-1]);
                }
            } , "login");
        }
        
        if (is_submit && error == false) {
            $loginCompents.checkUserName($form.find("input[name=username]") , function (object , response) {
                if (response.code !== 0) { //用户已存在
                    return $loginCompents.showError(object , $loginCompents.lang.username[-1]);
                }
                var params = {
                    "username" : $form.find("input[name=username]").val(),
                    "password" : $form.find("input[name=password]").val(),
                    "code" : $form.find("input[name=captcha]").val()
                };
                $.ajax({
                    "url"  : '/flow/auth/dologin',
                    "data" : params , 
                    "type" : "POST" ,
                    "dataType" : "JSON" , 
                    "success"  : function (result) {
                        if (result.code === 0) { // -_- ! Dont't care the word spellin
                            window.location.reload(); //登录成功
                        } else {
                            if (result.code === -400601 && !$('.jym').hasClass('hide')) {
                                alert('验证码错误！');
                                $(document.getElementById("checkcode")).click();
                            } else {
                                alert('用户名密码错误！');
//                                if (result.code_num > 3) {
//                                    $('.jym').removeClass('hide');
//                                    $('#checkcode').click();
//                                }
                            }
                        }
                    }
                });
            } , "login");
        }
    },
    
    //注册校验
    "registFormValidate" : function () {
        var error = false;
        var is_submit = ($(this).attr("id") == 'regist_btn');
        var name_type = 0;
        var $form = $("#regist_form");
        var object_name = (!this.name) ? "" : this.name; //表单名
        //
        if (!is_submit) {
            $loginCompents.hideError(this); //关闭层显示
        }
        //校验密码
        if (object_name == "password" || is_submit) {
            var code = ($loginCompents._validatePassword($form.find('input[name=password]').val())); 
            if (code<0) {
                $loginCompents.showError($form.find("input[name=password]") , $loginCompents.lang.password[code]);
                error = true;
            } else {
                if ($form.find("input[name=password2]").val()) {
                    object_name = "password2";
                }
            }
        }
        //校验密码
        if (object_name == "password2" || is_submit) {
            var code = $loginCompents._validateConfirmPassword(
                $form.find('input[name=password2]').val(),
                $form.find('input[name=password]').val()
            ); 
            if (code<0) {
                $loginCompents.showError($form.find("input[name=password2]") , $loginCompents.lang.confirmPassword[code]);
                error = true;
            }
        }
        
        //校验码错误
        if (object_name == "captcha" || is_submit) {
            var code = $loginCompents._validateCaptcha($form.find("input[name=captcha]").val());
            if (code<0) {
                $loginCompents.showError($form.find("input[name=captcha]") , $loginCompents.lang.captcha[code]);
                error = true;
            }
        }
        //手机校验码 . 用户名为手机号是触发.
        if (object_name == "verify_code" || (is_submit && $loginCompents._validateMobilePhone($form.find("input[name=username]").val()))) {
            var code = $loginCompents._validateVerfiyCode($form.find("input[name=code]").val());
            if (code<0) {
                $loginCompents.showError($form.find("input[name=code]") , $loginCompents.lang.captcha[code]);
                error = true;
            }
        }
        //用户名校验
        if (object_name == "username") {
            return $loginCompents.checkUserName($form.find("input[name=username]") , function (object , response) {
                if (response.code !== 0) { //用户已存在
                    return $loginCompents.showError(object , $loginCompents.lang.regist[3]);
                }
            } , "regist");
        }
        
        if (is_submit && error == false) {
            //注册
            if (typeof($form.find("input[name=confirm]").attr("checked")) == "undefined") {
                return alert($loginCompents.lang.regist[9]);
//                return $loginCompents.showError($form.find("input[name=confirm]") , $loginCompents.lang.regist[9]);
            }
            $loginCompents.checkUserName(
                $form.find("input[name=username]") , 
                function (object , response) {
                    if (response.code !== 0) { //用户已存在
                        return $loginCompents.showError(object , $loginCompents.lang.regist[3]);
                    }
                    var username = $form.find("input[name=username]").val();
                    
                    var regist_type = $loginCompents._validateUserName(username);
                    if (regist_type == 2) {
                        var params = {
                            "username"  : $form.find("input[name=username]").val(),
                            "password" : $form.find("input[name=password]").val(),//"password s" -_ - ! wtf
                            "verifyCode"   : $form.find("input[name=code]").val(),
                            "nameType"  : "mobile"
                        };
                    } else { //邮箱注册
                        var params = {
                            "username"     : $form.find("input[name=username]").val(),
                            "password"  : $form.find("input[name=password]").val(),//找你妹...
                            "code"      : $form.find("input[name=captcha]").val(),
                            "nameType"  : "email"
                        };
                    }
                    $.ajax({
                        "url" : '/flow/auth/doregist',
                        "data" : params , 
                        "type" : "POST",
                        "dataType" : "JSON" , 
                        "success" : function (result) {
                            if (result.code === 0) {
                           
                                window.location.reload();
                            } else if (result.code === -400601) {
                                if (regist_type == 2) {
                                    $loginCompents.showError($form.find("input[name=code]") , $loginCompents.lang.regist[5]);
                                } else {
                                    $loginCompents.showError($form.find("input[name=captcha]") , $loginCompents.lang.regist[1]);
                                    $form.find(".yimg img").click(); //刷新验证码
                                }
                            } else if (result.code) {
                                alert ($loginCompents.lang.regist[0]);
                            }  else {
                                alert ("注册失败")
                            }
                        }
                    });
                } ,
                "regist"
            );
        }
    },
    
    //激活校验
    "activeFormValidate" : function () {
        var error = false;
        var is_submit = ($(this).attr("id") == 'active_btn');
        var name_type = 0;
        var $form = $("#active_form");
        var object_name = (!this.name) ? "" : this.name; //表单名
        //
        if (!is_submit) {
            $loginCompents.hideError(this); //关闭层显示
        }
        
        //校验密码
        if (object_name == "password" || is_submit) {
            var code = ($loginCompents._validatePassword($form.find('input[name=password]').val())); 
            if (code<0) {
                $loginCompents.showError($form.find("input[name=password]") , $loginCompents.lang.password[code]);
                error = true;
            } else {
                if ($form.find("input[name=password2]").val()) {
                    object_name = "password2";
                }
            }
        }
        //校验密码
        if (object_name == "password2" || is_submit) {
            var code = $loginCompents._validateConfirmPassword(
                $form.find('input[name=password2]').val(),
                $form.find('input[name=password]').val()
            ); 
            if (code<0) {
                $loginCompents.showError($form.find("input[name=password2]") , $loginCompents.lang.confirmPassword[code]);
                error = true;
            } else {
                $loginCompents.hideError($form.find("input[name=password2]")); 
            }
        }

        //手机校验码 . 用户名为手机号s时触发.
        if (object_name == "verify_code" || (is_submit && $loginCompents._validateMobilePhone($form.find("input[name=username]").val()))) {
            var code = $loginCompents._validateVerfiyCode($form.find("input[name=code]").val());
            if (code<0) {
                $loginCompents.showError($form.find("input[name=code]") , $loginCompents.lang.captcha[code]);
                error = true;
            }
        }
        //用户名校验
        if (object_name == "username") {
            return $loginCompents.checkActiveUsername($form.find("input[name=username]"));
        }
        
        if (is_submit && error == false) {
            //注册
            if (typeof($form.find("input[name=confirm]").attr("checked")) == "undefined") {
                return alert($loginCompents.lang.regist[9]);
//                return $loginCompents.showError($form.find("input[name=confirm]") , $loginCompents.lang.regist[9]);
            }
            $loginCompents.checkActiveUsername(
                $form.find("input[name=username]") , 
                function(object) {
                    var params = {
                        "user_name": $form.find("input[name=username]").val(),
                        "password": $form.find("input[name=password]").val(),
                        "verifyCode": $form.find("input[name=code]").val(),
                        "nameType" : "mobile"
                    };
                    $.ajax({
                        "url": "/flow/auth/doregist",
                        "data": params,
                        "type": "POST",
                        "dataType": "JSON",
                        "success": function(result) {
                            $('#btn3').removeAttr("disabled"); 
                            if (result.code === 0) {
                                window.location.reload();
                            } else if (result.code === -400601) {
                                $form.find("input[name=code]").val("");
                                $loginCompents.showError($form.find("input[name=code]"), result.content);
                            } else {
                                $loginCompents.showError($form.find("input[name=username]"), result.content);
                            }
                        }
                    });
                },
                "active"
            );
        }
    },
    
    "eventTabClick" : function (i) {
        //console.log(i);
        this.compent.find("#tab_con li").hide();
        //初始化表单内容
        $(this.compent.find("#tab_con li")[i]).show().find(".yimg img.yzm").click();
    }, 
    
    "eventCaptchaClick" : function () {
        var src = $(this).parents("label").find("img").attr("src")+'&' + Math.random();
        $(this).parents("label").find("img").attr("src" , src);
    },
    
    "eventCloseBtnClick" : function () {
        $loginCompents.compent.hide();
    },
    
    //发送手机验证码
    "eventVerfiyCodeClick" : function () {
        var btn = $("a.verfiy_code_btn");
        if ($loginCompents.verfiyCodeInterval <= 0) {
            
            var $form = $(this).parents("form");
            var input = $form.find("input[name=username]");
            var code = $form.find("input[name=captcha]");
            $loginCompents.hideError(input);
            $loginCompents.hideError(code);
            if (!$loginCompents._validateMobilePhone(input.val())) {
                return $loginCompents.showError(input, $loginCompents.lang.username[-2]);
            }
            
            var error = $loginCompents._validateCaptcha(code.val());
            if (error != true) {
                return $loginCompents.showError(code, $loginCompents.lang.captcha[error]);
            }
            $loginCompents.hideError($form.find("input[name=code]"));
            //发送验证码
            $.ajax({
                "url": "/flow/auth/sendVerifyCode/",
                "type" : "POST" ,
                "dataType" : "JSON",
                "data": {
                    "username": input.val(),
                    "code" : code.val(),
                },
                "success": function(response) {
                    switch (response.code) {
                        case -400601 :  $loginCompents.showError($form.find("input[name=captcha]"), "验证码错误。");
                            $form.find(".yimg img").click();//刷新
                            break;
                        case -400604 :  $loginCompents.showError($form.find("input[name=code]"), "每日验证码发送次数已达到上线。");
                            $form.find(".yimg img").click();//刷新
                            break; 
                        case 0 :
                            btn.parent().find("input[name=code]").attr("readonly", false);
                            $loginCompents.verfiyCodeInterval = 90;
                            btn.addClass('get_code2').removeClass('get_code');
                            $loginCompents.timeCounter();    
                            break;
                        default :
                            $loginCompents.showError($form.find("input[name=code]"), "发送验证码失败，请稍后再试");
                    }
                }
            });
//            btn.parent().find("input[name=code]").attr("readonly",false);
//            $loginCompents.verfiyCodeInterval = 90;
//            btn.addClass('get_code2').removeClass('get_code');
//            $loginCompents.timeCounter();
        } 
    } ,
    
    "timeCounter": function() {
        var btn = $("a.verfiy_code_btn");
        btn.html("(" + $loginCompents.verfiyCodeInterval + "秒后)重新获取");
        $loginCompents.verfiyCodeInterval--;
        if ($loginCompents.verfiyCodeInterval > 0) {
            setTimeout($loginCompents.timeCounter, 1000);
        } else {
            btn.html("重新获取校验码").addClass('get_code').removeClass('get_code2');
        }
    },
    /**
     * -------
     * 校验声明
     * -------
     */
    
    /**
     * 检测用户名
     * @param object object
     * @param function callback (object , data)
     * @param bool is_regist
     * @returns {undefined}
     */
    "checkUserName" : function (object , callback , type) {
        var val = $(object).val();
        var code = ($loginCompents._validateUserName(val));
        if (type == "login") {
            if (code < 0) {
                $loginCompents.showError(object, $loginCompents.lang.username[code]);
                return;
            }
        } else {
            if (code <= 0) {
                $loginCompents.showError(object, $loginCompents.lang.username[code]);
                return;
            }
        }
        

        if (type == "regist") {
            var $form = $(object).parents("form");
            if (code == 1) {
                $form.find("div#verify_code_div").hide();
            } else {
                $form.find("div#verify_code_div").show();
            }
        } else if (type == "active") {
            if (code !== 2) {
                $loginCompents.showError(object, $loginCompents.lang.username[-2]);
                return;
            }
        }
        
        $.ajax({
            "url" : '/flow/auth/checkUser',
            "data" : {
                "username":val,
                "for" : (type == "login")?"login":"regist"
            } , 
            "dataType": "json",
            "success" : function (data) {
                callback (object , data);
            }
        });
        return ;
    } ,
    
    /**
     * 查看帐号是否激活
     * @param object object
     * @param function[object] callback
     * @returns null
     */
    "checkActiveUsername" : function (object , callback) {
        $loginCompents.checkUserName(object, function (object, data) {
            if (data != "true") { //用户已存在
                return $loginCompents.showError(object, $loginCompents.lang.regist[3]);
            }
            //查看比酷是否有此用户
            $.ajax({
                "url" : "/flow/auth/checkuser",
                "data" : {"user_name" : object.val() , "for":"regist"},
                "dataType" : "JSON",
                "success" : function (response) {
                    if (response == "false" || response.code !==0 || response.data!==2) {
                        return $loginCompents.showError(object, "号码不存在，请核对后重新输入");
                    }
                    if (callback && typeof(callback) == "function") {
                        callback(object);
                    }
                } 
            });
        }, "regist");
    } ,
    /**
     * 校验用户名
     * @returns 0错误 , 2手机号 , 1邮箱 , -2 手机号码错误 , -1 邮箱格式错误 -3长度不符 , -4为空
     */
    "_validateUserName" : function (val) {
        if (!val || val.length == 0) {
            return -4;
        }
        if (val.lenth < 6 || val.length >45) {
            return -3;
        }
        if (!val.match(/^[a-zA-Z0-9@_\-\.]*$/)) {
            return -5; //非法字符
        }
        if (val.match(/^1[35798]\d{9,9}$/)) {
            return (this._validateMobilePhone(val)) ? 2 : -2;
        }
        if (val.match(/@/i)) {
            return (this._validateEmail(val)) ? 1 : -1;
        }
        
        return 0;
    } ,
    
    "_validateMobilePhone" : function (val) {
        if (typeof (val) == 'number') {
            val = val.toString();
        } else if (typeof(val) != 'string') {
            return false;
        }
        var m = val.match(/^(13|15|18|17)\d{8,10}$/);
        return m !== null;
    },
    
    "_validateEmail" : function (val) {
        if (typeof (val) != 'string') {
            val = val.toString();
        }
        var parent = /^\w+([-+\.]\w+)*@\w+([-.]\w+)*\.[a-z]{2,3}$/;
        return parent.test(val);
    },
    
    "_validatePassword" : function (val) {
        if (!val) {
            return -4;
        }
        if (val.length<6 || val.length>20) {
            return -3;
        }
//        if (!val.match(/^[a-zA-Z0-9\_\-\@\#\$\%\!\^\&\*]$/)) {
//            return -2;
//        }
        return true;
    },
    
    "_validateConfirmPassword" : function (val , val1) {
        if (!val) {
            return -4;
        }
        if (val.length<4 || val.length>20) {
            return -3;
        }
        if (val !== val1) {
            return -2;
        }
        return true;
    } ,
    
    "_validateCaptcha" : function (val) {
        if (val.length !== 4) {
            return -3;
        }
        if (!val.match(/^[a-zA-Z0-9]{4,4}$/)) {
            return -4;
        } 
        return true;
    } ,
    
     "_validateVerfiyCode" : function (val) {
        if (!val.match(/^[0-9]{4,6}$/)) {
            return -4;
        } 
        return true;
    } ,   
};

/**
 * 显示登录窗
 * @returns {undefined}
 */
function show_login () {
    $loginCompents.showLogin();
}